package com.agileai.portal.portlets.wcmlist;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.PortletPreferences;
import javax.portlet.ProcessAction;
import javax.portlet.ReadOnlyException;
import javax.portlet.RenderMode;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ValidatorException;
import javax.servlet.http.HttpServletRequest;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.domain.DataRow;
import com.agileai.hotweb.common.StringTemplateLoader;
import com.agileai.portal.bizmoduler.wcm.InfomationManage;
import com.agileai.portal.driver.GenericPotboyPortlet;
import com.agileai.portal.driver.common.PortletRequestHelper;
import com.agileai.portal.driver.common.PreferenceException;
import com.agileai.portal.driver.common.PreferencesHelper;
import com.agileai.portal.driver.common.PreferencesWrapper;
import com.agileai.portal.portlets.PortletCacheManager;
import com.agileai.util.StringUtil;

import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;

public class RelativeInfoList extends GenericPotboyPortlet {
	protected static final String ContentIdParamModeByParse = "byParse";
	protected static final String ContentIdParamModeByRetrieve = "byRetrieve";
	
	@RenderMode(name = "view")
	public void view(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PortletPreferences preferences =  PreferencesHelper.getPublicPreference(request);
		String templateId = preferences.getValue("templateId", null);
		String contentIdParamKey = preferences.getValue("contentIdParamKey", null);
		String contentIdParamMode = preferences.getValue("contentIdParamMode", ContentIdParamModeByRetrieve);
		
		if (!StringUtil.isNullOrEmpty(templateId) 
				&& !StringUtil.isNullOrEmpty(contentIdParamKey)
				&& !StringUtil.isNullOrEmpty(contentIdParamMode)){
			request.setAttribute("isSetting", "Y");
		}else{
			request.setAttribute("isSetting", "N");
		}
		
		String isSetting = (String)request.getAttribute("isSetting");
		if ("Y".equals(isSetting)){
			String contentId =  null;
			HttpServletRequest httpServletRequest = PortletRequestHelper.getRequestContext(request).getServletRequest();
			if (ContentIdParamModeByRetrieve.equals(contentIdParamMode)){
				contentId = httpServletRequest.getParameter(contentIdParamKey);				
			}else{
				contentId = (String)httpServletRequest.getAttribute(contentIdParamKey);
			}
			if (StringUtil.isNullOrEmpty(contentId)){
				request.setAttribute("content", "content is not defined,please check it !");
			}else{
				InfomationManage infomationManage = this.lookupService(InfomationManage.class);
				DataRow row = infomationManage.getContentRecord(contentId);
				try {
					String relInfoIds = row.getString("INFO_REL_INFOIDS");
					JSONArray jsonArray = this.buildInfoIdJsonArray(relInfoIds);
		            List<String> infoIdList = new ArrayList<String>();
		            for (int i=0;i < jsonArray.length();i++){
		            	JSONObject jsonObject = jsonArray.getJSONObject(i);
		            	String infoId = jsonObject.getString("infoId");
		            	infoIdList.add(infoId);
		            }
		        	List<DataRow> records = infomationManage.findRefInfoRecords(infoIdList);
					InfomationsModel infoListModel = new InfomationsModel();
					infoListModel.getRecordList().addAll(records);
					
					String urlPrefix = PortletCacheManager.buildDataURLPefix(request);
					String tempateURL = urlPrefix+"/resource?PortletTemptProvider&actionType=retrieveContent&contentId="+templateId;
					String template = PortletCacheManager.getOnly().getCachedData("Y", tempateURL, "0");

					StringWriter writer = new StringWriter();
					generate(infoListModel, template, writer);
					String html = writer.toString();
					request.setAttribute("content", html);
				} catch (Exception e) {
					request.setAttribute("content", "retrive content error,please check it !");
				}
			}
		}
		super.doView(request, response);
	}
	
    private JSONArray buildInfoIdJsonArray(String relInfoIds){
    	JSONArray result = new JSONArray();
    	try {
            if (!StringUtil.isNullOrEmpty(relInfoIds)){
            	result = new JSONArray(relInfoIds);
        	}
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
		}    
		return result;
    }
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void generate(InfomationsModel infoListModel,String template,StringWriter writer) {
		String encoding = "utf-8";
		try {
        	Configuration cfg = new Configuration();
        	cfg.setTemplateLoader(new StringTemplateLoader(template));  
        	cfg.setEncoding(Locale.getDefault(), encoding);
            cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
        	Template temp = cfg.getTemplate("");
        	temp.setEncoding(encoding);
            Map root = new HashMap();
            root.put("model",infoListModel);
            temp.process(root, writer);
            writer.flush();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	@RenderMode(name = "edit")
	public void edit(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
		String templateId = preferences.getValue("templateId", null);
		String contentIdParamKey = preferences.getValue("contentIdParamKey", "contentId");
		String contentIdParamMode = preferences.getValue("contentIdParamMode", ContentIdParamModeByRetrieve);
		
		request.setAttribute("templateId", templateId);
		request.setAttribute("contentIdParamKey",contentIdParamKey);
		request.setAttribute("contentIdParamMode", contentIdParamMode);
		super.doEdit(request, response);
	}

	@ProcessAction(name = "saveConfig")
	public void saveConfig(ActionRequest request, ActionResponse response)
			throws ReadOnlyException, PortletModeException, ValidatorException,
			IOException, PreferenceException {
		String templateId = request.getParameter("templateId");
		String contentIdParamKey = request.getParameter("contentIdParamKey");
		String contentIdParamMode = request.getParameter("contentIdParamMode");
		
		PreferencesWrapper preferWapper = new PreferencesWrapper();		
		preferWapper.setValue("templateId", templateId);
		preferWapper.setValue("contentIdParamKey", contentIdParamKey);
		preferWapper.setValue("contentIdParamMode", contentIdParamMode);
		
		PreferencesHelper.savePublicPreferences(request, preferWapper.getPreferences());	
		response.setPortletMode(PortletMode.VIEW);
	}
}
